package com.lifp.controller;

import cn.hutool.core.io.resource.UrlResource;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.lifp.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author lifp
 * @date 2023/04/24
 */
@Api(tags = "PDF模板")
@RestController
@RequestMapping("/template")
public class TemplateController {

    private static final String TEMP_PATH = "C:\\Users\\lenovo\\Desktop\\contract.pdf";

    //宋体
    private static final String FONT_PATH = "C:\\Windows\\Fonts\\simsun.ttc,0";

    @SneakyThrows
    @ApiOperation("本地模板导出")
    @GetMapping(value = "/local/download", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> localDownload() {

        PdfReader pdfReader = new PdfReader(TEMP_PATH);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter pdfWriter = new PdfWriter(outputStream);

        PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

        //获取表单域
        PdfAcroForm acroForm = PdfAcroForm.getAcroForm(pdfDocument, false);
        Map<String, PdfFormField> formFields = acroForm.getFormFields();
        //创建字体
        //PdfFont font = PdfFontFactory.createFont(FONT_PATH);
        //颜色 黑色
        DeviceRgb color = new DeviceRgb(0, 0, 0);

        Map<String, String> formData = new HashMap<>();
        formData.put("contractNumber","HT-20122545");
        formData.put("buyerCompanyName","XXX科技有限公司");
        formData.put("sellerCompanyName","兰州xxx信息技术有限公司");

        //设置值
        Set<String> formFieldSet = formFields.keySet();

        for (String formFieldName : formFieldSet) {
            if(formData.containsKey(formFieldName)){
                acroForm.getField(formFieldName)
                        .setValue(formData.get(formFieldName))
                        //.setFont(font)
                        .setColor(color);
            }
        }
        //去掉标识域
        acroForm.flattenFields();
        pdfDocument.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=hello.pdf");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }

    @SneakyThrows
    @ApiOperation("网络模板导出")
    @GetMapping(value = "/net/download", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> netDownload() {
        String fileUrl = "http://192.168.100.233:9002/gjmc/2023/04/22/20230422170359A018.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=yy6vI3LgF1tyniez%2F20230422%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230422T090359Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=41fc8e83cc43515365ef599eb9b06717f05b94cde72147126ee54d239a2e8ce4";
        //String fileUrl = "http://localhost:8081/contract1.pdf";

        InputStream inputStream = FileUtil.getInputStreamByUrl(fileUrl);

        //File file = FileUtil.getFileFromUrl(fileUrl);

        PdfReader pdfReader = new PdfReader(inputStream);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter pdfWriter = new PdfWriter(outputStream);

        PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

        //获取表单域
        PdfAcroForm acroForm = PdfAcroForm.getAcroForm(pdfDocument, false);
        Map<String, PdfFormField> formFields = acroForm.getFormFields();
        //创建字体
        PdfFont font = PdfFontFactory.createFont(FONT_PATH);
        //颜色 黑色
        DeviceRgb color = new DeviceRgb(0, 0, 0);

        Map<String, String> formData = new HashMap<>();
        formData.put("contractNumber","HT-20122545");
        formData.put("buyerCompanyName","XXX科技有限公司");
        formData.put("sellerCompanyName","兰州xxx信息技术有限公司");

        //设置值
        Set<String> formFieldSet = formFields.keySet();

        for (String formFieldName : formFieldSet) {
            if(formData.containsKey(formFieldName)){
                acroForm.getField(formFieldName)
                        .setValue(formData.get(formFieldName))
                        .setFont(font)
                        .setColor(color);
            }
        }
        //去掉标识域
        acroForm.flattenFields();
        pdfDocument.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=hello.pdf");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }

    @SneakyThrows
    @ApiOperation("urlResource")
    @GetMapping(value = "/url/resource", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> urlResource(){
        UrlResource urlResource = new UrlResource(new URL("http://192.168.237.1:8080/contract.pdf"));
        InputStream inputStream = urlResource.getStream();

        PdfReader pdfReader = new PdfReader(inputStream);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter pdfWriter = new PdfWriter(outputStream);

        PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);
        pdfDocument.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=hello.pdf");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }
}
